package com.itheima.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.ResultData;
import com.itheima.domain.UmsAdmin;
import com.itheima.domain.UmsMenu;
import com.itheima.dto.AdminPasswordDto;
import com.itheima.exception.BusinessException;
import com.itheima.interceptor.AdminHolder;
import com.itheima.manager.AdminManager;
import com.itheima.service.UmsAdminService;
import com.itheima.service.UmsMenuService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
public class AdminController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @DubboReference
    UmsAdminService umsAdminService;
    @DubboReference
    UmsMenuService umsMenuService;
    @Autowired
    private AdminManager adminManager;

    //用户登录
    @PostMapping("/admin/login")
    public ResultData login(@RequestBody UmsAdmin umsAdmin) {
        UmsAdmin user = umsAdminService.findUserByName(umsAdmin.getUsername());
        if (user == null) {
            throw new BusinessException("该用户名尚未注册");
        }

        if (!StrUtil.equals(user.getPassword(), SecureUtil.md5(umsAdmin.getPassword()))) {
            throw new BusinessException("密码错误");
        }
        user.setPassword(null);
        String token = JwtUtil.createToken(BeanUtil.beanToMap(user));
        //将token作为key,用户的json数组作为value写到redis中,时效1小时
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, JSON.toJSONString(user), Duration.ofHours(1));
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("tokenHead", "Bearer ");
        resultMap.put("token", token);

        return ResultData.ok(resultMap, "登录成功");
    }

    //获取当前用户信息
    @GetMapping("/admin/info")
    public ResultData findUserByName(String userName){
        UmsAdmin admin = AdminHolder.get();
        HashMap<String,Object> data = new HashMap<>();
        String roles = umsAdminService.findRolesById(admin.getId());
        data.put("roles",roles);
        data.put("icon",admin.getIcon());
        List<UmsMenu> Menus =  umsMenuService.getMenuByUserId(admin.getId());
        data.put("menus",Menus);
        data.put("username",admin.getUsername());
        return ResultData.ok(data,"");
    }
    // 根据用户和姓名分页查询
    @GetMapping("/admin/list")
    public ResultData getAdminByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                     String keyword){
        return adminManager.getAdminByPage(pageNum, pageSize, keyword);

    }

    // 获取指定用户信息
    @GetMapping("/admin/{id}")
    public ResultData userInfo(@PathVariable("id") Long id){
        return adminManager.getUserInfo(id);

    }
    // 删除指定用户信息
    @PostMapping("/admin/delete/{id}")
    public ResultData delete(@PathVariable Integer id){
        return adminManager.delete(id);
    }


    // 获取指定用户角色
    @GetMapping("/admin/role/{adminId}")
    public ResultData updateById(@PathVariable Long adminId){
        return adminManager.getRolesInfo(adminId);
    }

    // 用户退出
    @PostMapping("/admin/logout")
    public ResultData logout(){
        return adminManager.logOut();
    }


    // 用户注册
    @PostMapping("/admin/register")
    public ResultData register(@RequestBody UmsAdmin umsAdmin){
        return adminManager.register(umsAdmin);
    }
    // 给用户角色分配
    @PostMapping("/admin/role/update")
    public ResultData updateAdminRole(@RequestParam("adminId") Long adminId,
                                      @RequestParam("roleIds") List<Long> roleIds){
        return adminManager.updateAdminRole(adminId, roleIds);
    }

    // 修改指定用户信息
    @PostMapping("/admin/update/{id}")
    public ResultData update(@PathVariable("id") Integer id,
                             @RequestBody UmsAdmin umsAdmin){
        return adminManager.update(umsAdmin);
    }

    // 修改账户状态
    @PostMapping("/admin/updateStatus/{id}")
    public ResultData updateStatus(@PathVariable("id") Integer id,
                                   @RequestParam Map<String, Object> map){

        Integer status = Integer.parseInt(String.valueOf(map.get("status")));
        return adminManager.updateStatus(id, status);
    }

    // 修改密码
    @PostMapping("/admin/updatePassword")
    public ResultData updatePassword(@RequestBody AdminPasswordDto adminPasswordDto){
        return adminManager.updatePassword(adminPasswordDto);
    }

    /*// 刷新token
    @GetMapping("/admin/refreshToken")
    public ResultData refreshToken(){
        Map<String, Object> map = adminManager.refreshToken();
        return ResultData.ok(map, "操作成功");
    }*/
}